package com.carsystem.service;

import com.carsystem.entity.Login;
import com.carsystem.entity.Permission;
import com.carsystem.entity.Role;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Reference
    private LoginService loginService;
    @Reference
    private IRoleService roleService;
    @Reference
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = loginService.selectByUsername(username);
        if (login==null){
            throw new UsernameNotFoundException("用户名不正确");
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();
        ////查角色
        //List<Role> roleList = roleService.selectByUid(login.getId());
        //if (roleList!=null && roleList.size()>0){
        //    for (Role role : roleList) {
        //        String keyword = role.getKeyword();
        //        if (!keyword.isEmpty()){
        //            authorityList.add(new SimpleGrantedAuthority(keyword));
        //        }
        //    }
        //}
        ////查权限
        //List<Permission> permissionList = permissionService.selectByUid(login.getId());
        //if (permissionList!=null && permissionList.size()>0){
        //    for (Permission permission : permissionList) {
        //        String keyword = permission.getKeyword();
        //        if (!keyword.isEmpty()){
        //            authorityList.add(new SimpleGrantedAuthority(keyword));
        //        }
        //    }
        //}
        return new User(username,login.getPassword(),authorityList);
    }
}
